package cn.fl.risk.controller;

import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPrdBscInfoService;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPrdBscInfoVO;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.risk.condition.RskArreExpLogMQC;
import cn.fl.risk.service.IRskArreExpLogMService;
import cn.fl.risk.vo.RskArreExpLogDVO;
import cn.fl.risk.vo.RskArreExpLogMVO;
import cn.fl.spl.utils.FileUtil;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 支付表欠款明细导出记录主表 控制层
 */
@Controller
@RequestMapping("/risk/rskArreExpLogM")
public class RskArreExpLogMController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(RskArreExpLogMController.class);

	/**
	 * RskArreExpLogM 服务层BEAN
	 */
	@Autowired
	private IRskArreExpLogMService rskArreExpLogMService;
	/**
	 * 数据字典
	 */
	@Autowired
	private ISysDictionaryApiService  sysDictionaryApiService;
	@Autowired
	private IPrjBscInfoService  prjBscInfoService;
	
	@Autowired
	private IPrjPrdDtlService  prjPrdDtlService;
	@Autowired
	private IPrjPrdBscInfoService  prjPrdBscInfoService;
	
	@Autowired
	private IPrjPrdPaySchMService  prjPrdPaySchMService;

	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("risk/rskArreExpLog/rskArreExpLogList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("risk/rskArreExpLogM/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("risk/rskArreExpLog/rskArreExpLogMDetail");
		RskArreExpLogMVO   logMVO = this.rskArreExpLogMService.selectRskArreExpLogMAndDetailById(Long.valueOf(id));
		PrjPrdPaySchMVO schM = prjPrdPaySchMService.selectPrjPrdPaySchMAndDetailById(logMVO.getPaySchId());
		PrjBscInfoVO prjbscinfo = this.prjBscInfoService.selectById(schM.getPrjId());
		//产品明细、产品价格
		PrjPrdDtlQueryCondition dtlQc = new PrjPrdDtlQueryCondition();
		dtlQc.setPaySchId(logMVO.getPaySchId());
		List<PrjPrdDtlVO>  dtlList = this.prjPrdDtlService.selectList(dtlQc);
		PrjPrdDtlVO dtlVO  = null;
		PrjPrdBscInfoVO prjPrdBscInfoVO = null;
		   String priceStr = "";
		   double price = 0;
		if(CollectionUtils.isNotEmpty(dtlList)){
			dtlVO = dtlList.get(0);
			prjPrdBscInfoVO = this.prjPrdBscInfoService.selectById(dtlVO.getPrjPrdId());
			   price = prjPrdBscInfoVO.getGuidePc() == null ? 0 : DecimalUtils.convertFenToYuan(prjPrdBscInfoVO.getGuidePc().longValue());
			   BigDecimal bd = new BigDecimal(price);
               priceStr = bd.toPlainString();
		}
		ListPageVO<RskArreExpLogDVO> detailLogListPage = new ListPageVO<RskArreExpLogDVO>(logMVO.getLogDList(),logMVO.getLogDList().size());
		view.addObject("detailLogListPage", JSON.toJSONString(detailLogListPage));
		view.addObject("dtl", dtlVO);
		view.addObject("prjPrdBscInfo", prjPrdBscInfoVO);
		view.addObject("priceStr", priceStr);
		view.addObject("prjbscinfo", prjbscinfo);
		view.addObject("id", id);
		view.addObject("schM", schM);
		view.addObject("logMVO", logMVO);
		BaseLogUtils.info(logger, "toDetailPage", "跳转到详情页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到导出页面
	 */
	@RequestMapping(value = "/toExportPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toExportPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("risk/rskArreExpLog/rskArreExpLogMExport");
		List<KeyValueVO> penaCalWayList = this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_PENA_CAL_WAY_CD,CurrentThreadContext.getCurrentSysCd() , CurrentThreadContext.getCurrentOrgCd());
		List<KeyValueVO> expWayList = this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_EXP_WAY_CD,CurrentThreadContext.getCurrentSysCd() , CurrentThreadContext.getCurrentOrgCd());
		view.addObject("expWayList", expWayList);
		view.addObject("penaCalWayList", penaCalWayList);
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toExportPage", "跳转到导出页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstNm = request.getParameter("cstNm");
		String lsCntNo = request.getParameter("lsCntNo");
		String paySchNo = request.getParameter("paySchNo");
		String stDt = request.getParameter("stDt");
		String endDt = request.getParameter("endDt");
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		RskArreExpLogMQC qc = new RskArreExpLogMQC();
		if (StringUtils.isNotEmpty(cstNm)) {
			qc.setCstNm(cstNm);
		}
		
		if (StringUtils.isNotEmpty(lsCntNo)) {
			qc.setLsCntNo(lsCntNo);
		}
		if (StringUtils.isNotEmpty(paySchNo)) {
			qc.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotEmpty(stDt)) {
			qc.setStDt(DateUtils.formatStringToDate(stDt, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(endDt)) {
			qc.setEndDt(DateUtils.formatStringToDate(endDt, DateUtils.YYYY_MM_DD));
		}
		page.setCondition(qc);

		Pager pager = this.rskArreExpLogMService.searchListPage(page);
		List<RskArreExpLogMVO> list = (List<RskArreExpLogMVO>) pager.getResultList();
		ListPageVO<RskArreExpLogMVO> listPage = new ListPageVO<RskArreExpLogMVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.rskArreExpLogMService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			RskArreExpLogMVO vo = this.rskArreExpLogMService.selectRskArreExpLogMAndDetailById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		RskArreExpLogMVO entity = null;
		try {
			entity = new RskArreExpLogMVO();
			//TODO ADD PARAM
			Long id = this.rskArreExpLogMService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		RskArreExpLogMVO entity = null;
		try {
			entity = new RskArreExpLogMVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.rskArreExpLogMService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	 /**
	 *导出欠款明细信息
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/arreExport.do", method = { RequestMethod.POST})
	@ResponseBody
	public DataResultVO arreExport(HttpServletRequest request, HttpServletResponse response) {
	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		String ids = request.getParameter("ids");//ID列表
		String closDt = request.getParameter("closDt");
		String expPd = request.getParameter("expPd");
		String penaCalWay = request.getParameter("penaCalWay");
		String overdueClosDt = request.getParameter("overdueClosDt");
		
		if(StringUtils.isBlank(closDt)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"截至日期不能为空!");
		}
		if(StringUtils.isBlank(expPd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"应付金额导出期次不能为空!");
		}
		if(StringUtils.isBlank(penaCalWay)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"违约金计算方式不能为空!");
		}
		if(StringUtils.isBlank(overdueClosDt)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"逾期天数截止日期不能为空!");
		}
		RskArreExpLogMQC mqc = new RskArreExpLogMQC();
		List<Long> idList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idList.add(Long.valueOf(object.toString()));
		}
		mqc.setPayIdList(idList);
		mqc.setClosDt(DateUtils.formatStringToDate(closDt, DateUtils.YYYY_MM_DD));
		mqc.setExpPd(Integer.valueOf(expPd));
		mqc.setPenaCalWay(penaCalWay);
		mqc.setOverdueClosDt(DateUtils.formatStringToDate(overdueClosDt, DateUtils.YYYY_MM_DD));
		try {
			if(StringUtils.isNotBlank(ids)){
				//ByteArrayOutputStream out =  new ByteArrayOutputStream();
				
				String pdfName = "欠款明细("+DateUtils.getCurrentDateStr(DateUtils.YYYYMMDD)+")";
			    String strFileName = pdfName+".xls";
			    //文件保存路径
		        String filePath = CapitalConstant.CODE_PAY_LIST_FILE_SAVE_PATH;
		        String serverFilePath = FileUtil.getServerFilePath(filePath);
		        serverFilePath = serverFilePath  + pdfName + ".xlsx";
		        FileOutputStream   out = new FileOutputStream(serverFilePath);
			    /*response.setContentType("application/octet-stream");
			    response.setCharacterEncoding("UTF-8");
			    response.setHeader("Pragma", "public");
			    response.setHeader("Cache-Control",
			    		"must-revalidate, post-check=0, pre-check=0");
			    response.setDateHeader("Expires", 0);
			    if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
			    	strFileName = URLEncoder.encode(strFileName, "UTF-8");  
			    } else {  
			    	strFileName = new String(strFileName.getBytes("UTF-8"), "ISO8859-1");  
			    } 
			    response.setHeader("Content-Disposition",
			    		"attachment; filename=" + strFileName);
			    ServletOutputStream o = response.getOutputStream();*/
			    List<RskArreExpLogMVO> logMList =  this.rskArreExpLogMService.exportArreExcelData(mqc, out);
			    
		   	    /*out.writeTo(o);
		   	   o.flush();
		   	   o.close() ;*/
		   		//成功后插入导出数据记录信息
		   		boolean flag  = this.rskArreExpLogMService.addArreExpLogByCond(logMList);
		   		if(!flag){
		   			result.setSuccess(BaseConstant.IS_YESNO_NO);
		   		}
		   		
		   	  serverFilePath = serverFilePath.replace(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH),
		                PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
		        BaseLogUtils.info(logger, "exportPayList", "导出欠款明细数据,返回服务器路径.serverPath:" + serverFilePath);
		        result.setData(serverFilePath);
		        result.setInfo("导出成功");
		        result.setSuccess(BaseConstant.IS_YESNO_YES);
			}
			
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "exportPrjPrdPaySch", "导出支付表失败.[paySchId="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "exportPrjPrdPaySch", "导出支付表失败.[paySchId="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}



}

